﻿namespace HZY.Repository.EntityFramework.Admin;

/// <summary>
/// 程序启动器
/// </summary>
public class AdminRepositoryStartup : Startup<AdminRepositoryStartup>
{
    /// <summary>
    /// 程序启动器
    /// </summary>
    /// <param name="webApplicationBuilder"></param>
    public override void ConfigureServices(WebApplicationBuilder webApplicationBuilder)
    {
        var configuration = webApplicationBuilder.Configuration;
        var services = webApplicationBuilder.Services;

        var adminRepositoriesOptions = configuration.GetSection(nameof(AdminRepositoryOptions)).Get<AdminRepositoryOptions>();

        services.AddDbContextFactory<AdminDbContext>();

        #region 仓储注册

        var adminDbContextType = typeof(AdminDbContext);

        var interpreter = new Interpreter()
                .SetVariable(nameof(services), services)
                .Reference(typeof(ServiceCollectionServiceExtensions))
                .Reference(typeof(IRepository<>))
                .Reference(typeof(RepositoryImpl<,>))
                .Reference(adminDbContextType)
                ;

        var dbContextConfigAttribute = adminDbContextType.GetCustomAttribute<DbContextConfigAttribute>()!;

        // 将实体存储起来
        dbContextConfigAttribute.GetModelTypes(adminDbContextType).ForEach(s => EntityFrameworkRepositoriesUtil.AddDbContextAndEntityInfo(s, adminDbContextType));

        // 将实体与仓储接口注入到ioc
        EntityFrameworkRepositoriesUtil.GetDbContextAndEntityInfoAll()
            .Where(w => w.DbContextType.FullName == adminDbContextType.FullName)
            .ToList()
            .ForEach(item =>
            {
                interpreter.Reference(item.EntityType);
                var entity = item.EntityType.Name;
                var context = adminDbContextType.Name;

                var code = $"""
                services.AddScoped(typeof(IRepository<{entity}>),typeof(RepositoryImpl<{entity},{context}>))
                """;

                interpreter.Eval(code);
            });

        #endregion

    }

    /// <summary>
    /// Configure
    /// </summary>
    /// <param name="webApplication"></param>
    public override void Configure(WebApplication webApplication)
    {
        // 使用 DbContext
        #region 开发环境检测是否需要数据库迁移

        if (webApplication.Environment.IsDevelopment())
        {
            // 自动迁移 （如果迁移文件有变动）
            using var scope = webApplication.Services.CreateScope();
            using var adminDbContext = scope.ServiceProvider.GetService<AdminDbContext>();
            if (adminDbContext!.Database.GetPendingMigrations().Count() > 0)
            {
                try
                {
                    adminDbContext.Database.Migrate();
                }
                catch (Exception ex)
                {
                    LogUtil.Log.Error(ex.Message, ex);
                }
            }
        }

        #endregion

    }


}
